/*
 * Copyright Thoughtworks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { MithrilViewComponent } from "jsx/mithril-component";
import m from "mithril";
import Stream from "mithril/stream";
import { ButtonGroup, Cancel, Primary, Secondary } from "views/components/buttons";
import { FlashMessage, MessageType } from "views/components/flash_message";
import { Form, FormBody } from "views/components/forms/form";
import { CheckboxField, NumberField, PasswordField, TextField } from "views/components/forms/input_fields";
import { Delete, IconGroup } from "views/components/icons";
import { OperationState } from "views/pages/page_operations";
import { MailServerManagementAttrs } from "views/pages/server_configuration";
import styles from "./index.scss";
import { i18n } from "helpers/i18n";

export class MailServerManagementWidget extends MithrilViewComponent<MailServerManagementAttrs> {
  private ajaxOperationMonitor = Stream<OperationState>(OperationState.UNKNOWN);

  oninit(vnode: m.Vnode<MailServerManagementAttrs>) {
    // 设置当前页面上下文
    i18n.setCurrentPage("server-config");
  }

  view(vnode: m.Vnode<MailServerManagementAttrs>) {
    const mailServer = vnode.attrs.mailServerVM().entity();

    let message, icon;
    if (vnode.attrs.testMailResponse) {
      const msg = vnode.attrs.testMailResponse().hasMessage()
        ? vnode.attrs.testMailResponse().message
        : "Connection OK";
      message = <FlashMessage type={vnode.attrs.testMailResponse().type} message={msg} />;
      switch (vnode.attrs.testMailResponse().type) {
        case MessageType.alert:
          icon = <span class={styles.testConnectionFailure} data-test-id="test-connection-icon-alert" />;
          break;
        case MessageType.success:
          icon = <span class={styles.testConnectionSuccess} data-test-id="test-connection-icon-success" />;
          break;
      }
    }

    return (
      <div data-test-id="mail-server-management-widget" class={styles.formContainer}>
        <FormBody>
          <div class={styles.formHeader}>
            <h2>{i18n.tSyncForPage("admin.server.config.email.server.title", "server-config")}</h2>
            <div class={styles.deleteIcon}>
              <IconGroup>
                <Delete
                  data-test-id={"Delete"}
                  disabled={!vnode.attrs.mailServerVM().canDeleteMailServer()}
                  onclick={() => vnode.attrs.onMailServerManagementDelete()}
                >
                  {i18n.tSyncForPage("admin.server.config.email.server.delete", "server-config")}
                </Delete>
              </IconGroup>
            </div>
          </div>
          <div class={styles.formFields}>
            <Form compactForm={true}>
              <TextField
                label={i18n.tSyncForPage("admin.server.config.email.server.smtp.hostname", "server-config")}
                errorText={mailServer.errors().errorsForDisplay("hostname")}
                onchange={() => mailServer.validate("hostname")}
                property={mailServer.hostname}
                helpText={i18n.tSyncForPage("admin.server.config.email.server.smtp.hostname.help", "server-config")}
                required={true}
              />

              <NumberField
                label={i18n.tSyncForPage("admin.server.config.email.server.smtp.port", "server-config")}
                errorText={mailServer.errors().errorsForDisplay("port")}
                onchange={() => mailServer.validate("port")}
                property={mailServer.port}
                helpText={i18n.tSyncForPage("admin.server.config.email.server.smtp.port.help", "server-config")}
                required={true}
              />

              <CheckboxField
                label={i18n.tSyncForPage("admin.server.config.email.server.use.smtps", "server-config")}
                property={mailServer.tls}
                helpText={i18n.tSyncForPage("admin.server.config.email.server.use.smtps.help", "server-config")}
                docLink="/configuration/admin_mailhost_info.html#smtps-and-tls"
              />

              <TextField
                label={i18n.tSyncForPage("admin.server.config.email.server.smtp.username", "server-config")}
                errorText={mailServer.errors().errorsForDisplay("password")}
                onchange={() => mailServer.validate("password")}
                property={mailServer.username}
                helpText={i18n.tSyncForPage("admin.server.config.email.server.smtp.username.help", "server-config")}
              />

              <PasswordField
                label={i18n.tSyncForPage("admin.server.config.email.server.smtp.password", "server-config")}
                errorText={mailServer.errors().errorsForDisplay("password")}
                onchange={() => mailServer.validate("password")}
                property={mailServer.password}
                helpText={i18n.tSyncForPage("admin.server.config.email.server.smtp.password.help", "server-config")}
              />

              <TextField
                label={i18n.tSyncForPage("admin.server.config.email.server.send.email.using.address", "server-config")}
                errorText={mailServer.errors().errorsForDisplay("senderEmail")}
                onchange={() => mailServer.validate("senderEmail")}
                property={mailServer.senderEmail}
                required={true}
                helpText={i18n.tSyncForPage(
                  "admin.server.config.email.server.send.email.using.address.help",
                  "server-config"
                )}
              />

              <div class={styles.adminMail}>
                <div class={styles.adminMailInput}>
                  <TextField
                    label={i18n.tSyncForPage("admin.server.config.email.server.administrator.email", "server-config")}
                    errorText={mailServer.errors().errorsForDisplay("adminEmail")}
                    onchange={() => mailServer.validate("adminEmail")}
                    property={mailServer.adminEmail}
                    required={true}
                    helpText={i18n.tSyncForPage(
                      "admin.server.config.email.server.administrator.email.help",
                      "server-config"
                    )}
                  />
                </div>
                <Secondary
                  data-test-id="send-test-email"
                  ajaxOperation={() => vnode.attrs.sendTestMail(vnode.attrs.mailServerVM().entity())}
                >
                  {icon} {i18n.tSyncForPage("admin.server.config.email.server.send.test.email", "server-config")}
                </Secondary>
              </div>
              {message}
            </Form>
          </div>
          <div class={styles.buttons}>
            <ButtonGroup>
              <Cancel
                data-test-id={"cancel"}
                ajaxOperationMonitor={this.ajaxOperationMonitor}
                onclick={() => vnode.attrs.onCancel(vnode.attrs.mailServerVM())}
              >
                {i18n.tSyncForPage("admin.server.config.common.buttons.cancel", "server-config")}
              </Cancel>
              <Primary
                data-test-id={"save"}
                ajaxOperationMonitor={this.ajaxOperationMonitor}
                ajaxOperation={() => vnode.attrs.onMailServerManagementSave(vnode.attrs.mailServerVM().entity())}
              >
                {i18n.tSyncForPage("admin.server.config.common.buttons.save", "server-config")}
              </Primary>
            </ButtonGroup>
          </div>
        </FormBody>
      </div>
    );
  }
}
